package cn.explink.dop.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.explink.dop.dao.OrderDao;
import cn.explink.dop.entity.vo.DeliveryCompanyVO;
import cn.explink.dop.entity.vo.DeliveryManVO;
import cn.explink.dop.entity.vo.ExpressCompanyVO;
import cn.explink.dop.entity.vo.PostmanVO;
import cn.explink.dop.service.DeliveryCompanyService;
import cn.explink.dop.service.DeliveryManService;
import cn.explink.eap.core.common.model.json.AjaxJson;
import cn.explink.eap.core.constant.Globals;
import cn.explink.eap.core.util.PasswordUtil;
import cn.explink.eap.core.util.ResourceUtil;
import cn.explink.eap.core.util.StringUtil;
import cn.explink.eap.core.util.UUIDGenerator;
import cn.explink.eap.web.cgform.controller.autolist.CgAutoListController;
import cn.explink.eap.web.system.pojo.base.TSRole;
import cn.explink.eap.web.system.pojo.base.TSRoleUser;
import cn.explink.eap.web.system.pojo.base.TSUser;
import cn.explink.eap.web.system.service.SystemService;

/**
 *
 * @ClassName: DeliveryCompanyController
 * @Description: 配送公司管理Controller
 * @author 孟凡岭
 * @date 2015年5月25日 下午6:01:32
 * @since AR1.0
 */
@Controller
@RequestMapping("/deliveryCompanyController")
public class DeliveryCompanyController extends CgAutoListController {
	@Autowired
	private DeliveryCompanyService deliveryCompanyService;
	@Autowired
	private DeliveryManService deliveryManService;
	@Autowired
	private SystemService systemService;

	/**
	 *
	 * @Title: index
	 * @Description: 页面跳转
	 * @author 孟凡岭
	 * @param @param request
	 * @param @return
	 * @return ModelAndView 返回类型
	 * @throws
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("dop/deliveryCompany/deliveryCompany");
		return view;
	}

	/**
	 *
	 * @Title: queryList
	 * @Description: 分页查询
	 * @author 孟凡岭
	 * @param @param company
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @param request
	 * @param @return
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(params = "queryList")
	@ResponseBody
	public Map<String, Object> queryList(DeliveryCompanyVO company, int pageNum, int pageSize, HttpServletRequest request) {
		try {
			Map<String, Object> map = this.deliveryCompanyService.queryListByPage(company, pageNum, pageSize);
			return map;
		} catch (Exception e) {
			// TODO: handle exception
			return new HashMap<String, Object>();
		}
	}

	/**
	 *
	 * @Title: saveOrUpdate
	 * @Description: 保存或者更新数据
	 * @author 孟凡岭
	 * @param @param company
	 * @param @param request
	 * @param @return
	 * @return AjaxJson 返回类型
	 * @throws
	 */
	@RequestMapping(params = "saveOrUpdate")
	@ResponseBody
	public AjaxJson saveOrUpdate(DeliveryCompanyVO company, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			/**
			 * 如果id是空的，保存新数据
			 */
			if (StringUtils.isBlank(company.getId())) {
				company.setEmployeeNum(0);
				company.setStatus(1);
				
				List<DeliveryCompanyVO> deliverycompanylist = this.systemService.findByProperty(DeliveryCompanyVO.class, "companyName", company.getCompanyName());//找到这个公司名称在delivrycompany表中对应的记录
				List<ExpressCompanyVO> expresscompanylist = this.systemService.findByProperty(ExpressCompanyVO.class, "name", company.getCompanyName());//找到这个公司名称在express_company表中对应的记录
				//如果在express_company中存在该公司，并且这个公司名在deliverycompany中没有对应其他公司(此时该公司名可能对应company这一个公司，也可能不对应一个公司，即company之前没存公司名)
				if(expresscompanylist.size() > 0 && ((deliverycompanylist.size() == 1 && deliverycompanylist.get(0).getId().equals(company.getId())) || (deliverycompanylist.size() == 0))){
					ExpressCompanyVO expresscompanyMap = new ExpressCompanyVO();
					expresscompanyMap = expresscompanylist.get(0);	//如果在express_company表中找到了(仅会有一条)，所以不做判断了			
					company.setDeliverycompanyid(expresscompanyMap.getId());	//把express_company表中的id赋值给deliverycompany表中的deliverycompany_id
					
					this.deliveryCompanyService.save(company);
					j.setObj(company.getId());
					j.setSuccess(true);
				}else{
					j.setSuccess(false);
				}								
			} else {
				DeliveryCompanyVO vo = this.deliveryCompanyService.get(DeliveryCompanyVO.class, company.getId());
				vo.setCompanyDesc(company.getCompanyDesc());
				vo.setCompanyName(company.getCompanyName());
				vo.setCompanyTel(company.getCompanyTel());
				
				List<DeliveryCompanyVO> deliverycompanylist = this.systemService.findByProperty(DeliveryCompanyVO.class, "companyName", vo.getCompanyName());//找到这个公司名称在delivrycompany表中对应的记录
				List<ExpressCompanyVO> expresscompanylist = this.systemService.findByProperty(ExpressCompanyVO.class, "name", vo.getCompanyName());	//找到这个公司名称在express_company表中对应的记录
				//如果在express_company中存在该公司，并且这个公司名在deliverycompany中没有对应其他公司(此时该公司名可能对应company这一个公司，也可能不对应一个公司，即company之前没存公司名)
				if(expresscompanylist.size() > 0 && ((deliverycompanylist.size() == 1 && deliverycompanylist.get(0).getId().equals(vo.getId())) || (deliverycompanylist.size() == 0))){
					ExpressCompanyVO expresscompanyMap = new ExpressCompanyVO();
					expresscompanyMap = expresscompanylist.get(0);	//如果在express_company表中找到了(仅会有一条)，所以不做判断了			
					vo.setDeliverycompanyid(expresscompanyMap.getId());	//把express_company表中的id赋值给deliverycompany表中的deliverycompany_id
					
					this.deliveryCompanyService.updateEntitie(vo);
					j.setObj(vo.getId());
					j.setSuccess(true);
				}else{
					j.setSuccess(false);
				}								
			}			
		} catch (Exception e) {
			// TODO: handle exception
			j.setSuccess(false);
		}
		return j;
	}

	/**
	 *
	 * @Title: saveOrUpdateMan
	 * @Description: 保存或修改人员信息
	 * @author 孟凡岭
	 * @param @param man
	 * @param @param delId
	 * @param @param companyId
	 * @param @param user
	 * @param @param roleId
	 * @param @param request
	 * @param @return
	 * @return AjaxJson 返回类型
	 * @throws
	 */
	@RequestMapping(params = "saveOrUpdateMan")
	@ResponseBody
	public AjaxJson saveOrUpdateMan(DeliveryManVO man, String delId, String companyId, TSUser user, String roleId, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			DeliveryCompanyVO com = new DeliveryCompanyVO();
			com.setId(companyId);
			/**
			 * 如果员工ID不为空，对数据进行更新
			 */
			
			if (StringUtils.isNotBlank(delId)) {
				DeliveryManVO manVO = this.deliveryManService.get(DeliveryManVO.class, delId);
				TSUser sUser = this.systemService.get(TSUser.class, manVO.getUserId());
				sUser.setRealName(user.getRealName());
				List<TSRoleUser> ru = this.systemService.findByProperty(TSRoleUser.class, "TSUser.id", sUser.getId());
				this.systemService.deleteAllEntitie(ru);
				manVO.setDelName(user.getRealName());
				manVO.setDelCertificates(man.getDelCertificates());
				manVO.setDelTelephone(man.getDelTelephone());
				manVO.setDelIntroduction(man.getDelIntroduction());
				manVO.setIsDeliveryMan(man.getIsDeliveryMan());
				
				if(manVO != null && manVO.getDelCertificates() != null && !"".equals(manVO.getDelCertificates())){//如果没有填身份证号，那么不用对接,保存即可
					List<DeliveryManVO> deliverymanlist = this.systemService.findByProperty(DeliveryManVO.class, "delCertificates", manVO.getDelCertificates());//找到这个身份证号在delivryman表中对应的记录
					List<PostmanVO> postmanlist = this.systemService.findByProperty(PostmanVO.class, "idcardno", manVO.getDelCertificates());	
					//如果在postman中存在该配送员，并且这个身份证号在deliveryman中没有对应其他配送员(此时该身份证号可能对应manVO这个人，也可能不对应一个人，即manVO之前没存身份证号)
					if(postmanlist.size() > 0 && ((deliverymanlist.size() == 1 && deliverymanlist.get(0).getId().equals(manVO.getId())) || (deliverymanlist.size() == 0))){
						PostmanVO postmanMap = new PostmanVO();
						postmanMap = postmanlist.get(0);	//如果在postman表中找到了(仅会有一条)，所以不做判断了			
						manVO.setPostmanid(postmanMap.getId());	//把postman表中的id赋值给deliveryman表中的postman_id
						
						this.systemService.updateEntitie(sUser);
						this.systemService.updateEntitie(manVO);
						user = sUser;
						
						if (StringUtil.isNotEmpty(roleId)) {
							this.saveRoleUser(user, roleId);
						}
						j.setSuccess(true);
					}else{
						//如果在postman中没有找到对应的身份证号信息，那么不用保存
						j.setSuccess(false);
					}
				}else{//如果没有填写身份证号，那就只保存信息
					this.systemService.updateEntitie(sUser);
					this.systemService.updateEntitie(manVO);
					user = sUser;
					
					if (StringUtil.isNotEmpty(roleId)) {
						this.saveRoleUser(user, roleId);
					}
					j.setSuccess(true);					
				}
																							
			} else {
				user.setPassword(PasswordUtil.encrypt(user.getUserName(), user.getPassword(), PasswordUtil.getStaticSalt()));
				user.setTSDepart(null);
				user.setStatus(Globals.User_Normal);
				this.systemService.save(user);
				man.setDeliveryCompany(com);
				man.setsUser(user);
				man.setStatus(2);
				man.setType(1);
				man.setDelEnabled(1);
				man.setDelName(user.getRealName());
				
				if(man != null && man.getDelCertificates() != null && !"".equals(man.getDelCertificates())){//如果没有填身份证号，那么不用对接,保存即可					
					List<DeliveryManVO> deliverymanlist = this.systemService.findByProperty(DeliveryManVO.class, "delCertificates", man.getDelCertificates());//找到这个身份证号在delivryman表中对应的记录
					List<PostmanVO> postmanlist = this.systemService.findByProperty(PostmanVO.class, "idcardno", man.getDelCertificates());
					//如果在postman中存在该配送员，并且这个身份证号在deliveryman中没有对应其他配送员（此时，该身份证号应该对应0个人）
					if(postmanlist.size() > 0 && deliverymanlist.size() == 0 ){
						PostmanVO postmanMap = new PostmanVO();
						postmanMap = postmanlist.get(0);				
						man.setPostmanid(postmanMap.getId());//把postman表中的id赋值给deliveryman表中的postman_id	
						
						this.deliveryManService.save(man);
						this.deliveryCompanyService.updateEmployeeNum(companyId, 1, 1);
						
						if (StringUtil.isNotEmpty(roleId)) {
							this.saveRoleUser(user, roleId);
						}
						j.setSuccess(true);
					}else{
						j.setSuccess(false);
					}
				}else{	//如果没有填写身份证号，那就只保存信息			
					this.deliveryManService.save(man);
					this.deliveryCompanyService.updateEmployeeNum(companyId, 1, 1);
					
					if (StringUtil.isNotEmpty(roleId)) {
						this.saveRoleUser(user, roleId);
					}
					j.setSuccess(true);
				}				
																	
			}												
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			j.setSuccess(false);
		}
		return j;
	}

	/**
	 *
	 * @Title: checkUserName
	 * @Description: 验证用户名唯一性
	 * @author 孟凡岭
	 * @param @param userName
	 * @param @param request
	 * @param @return
	 * @return boolean 返回类型
	 * @throws
	 */
	@RequestMapping(params = "checkUserName")
	@ResponseBody
	public boolean checkUserName(String userName, HttpServletRequest request) {
		List<TSUser> roles = this.systemService.findByProperty(TSUser.class, "userName", userName);
		if (roles.size() > 0) {
			return false;
		}
		return true;
	}
	/**
	 * 
	* @Title: chekcDelCertificates 
	* @Description: 验证员工证件编号正确性(postman表中需要有该身份证号信息、本地deliveryman表中该身份证号只能对应一个人)
	* @author 小强
	* @param @param man
	* @param @param delId
	* @param @param companyId
	* @param @param user
	* @param @param roleId
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(params = "chekcDelCertificates")
	@ResponseBody
	public AjaxJson chekcDelCertificates(DeliveryManVO man, String delId, String companyId, TSUser user, String roleId, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map<String,Object> infomap = new HashMap<String,Object> ();
	
		if(man != null && man.getDelCertificates() != null && !"".equals(man.getDelCertificates())){//如果有身份证号,则校验
			List<DeliveryManVO> deliverymanlist = this.systemService.findByProperty(DeliveryManVO.class, "delCertificates", man.getDelCertificates());//找到这个身份证号在delivryman表中对应的记录
			List<PostmanVO> postmanlist = this.systemService.findByProperty(PostmanVO.class, "idcardno", man.getDelCertificates());	////找到这个身份证号在postman表中对应的记录
			//如果在postman中存在该配送员，且只有一条记录，并且这个身份证号在deliveryman中没有对应其他配送员(此时该身份证号可能对应manVO这个人，也可能不对应一个人，即manVO之前没存身份证号)
			if(postmanlist.size() == 1 && ((deliverymanlist.size() == 1 && deliverymanlist.get(0).getId().equals(man.getId())) || (deliverymanlist.size() == 0))){											
				j.setSuccess(true);
			}else{//出现异常，给前台一个反馈
				if(postmanlist.size() != 1){//如果该身份证号在postman中找到两条以上记录或不存在记录					
					infomap.put("postmansize", 1);							
				}else if((deliverymanlist.size() ==1 && !deliverymanlist.get(0).getId().equals(man.getId()) || deliverymanlist.size() > 1)){
					infomap.put("deliverymansize", 1);//如果该身份证号在deliveryman中对应到了其他的人员
				}
 				j.setSuccess(false);
			}
		}else{//如果没有填写身份证号，那校验通过				
			j.setSuccess(true);					
		}
		j.setAttributes(infomap);
		return j;
	}
	
	/**
	 * 
	* @Title: chekcCompanyName 
	* @Description: 验证公司名称的正确性(express_company表中需要有该公司名称信息、本地deliverycompany表中该公司名称只能对应公司)
	* @author 小强
	* @param @param company
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(params = "chekcCompanyName")
	@ResponseBody
	public AjaxJson chekcCompanyName(DeliveryCompanyVO company, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map<String,Object> infomap = new HashMap<String,Object> ();
		
		List<DeliveryCompanyVO> deliverycompanylist = this.systemService.findByProperty(DeliveryCompanyVO.class, "companyName", company.getCompanyName());//找到这个公司名称在delivrycompany表中对应的记录
		List<ExpressCompanyVO> expresscompanylist = this.systemService.findByProperty(ExpressCompanyVO.class, "name", company.getCompanyName());//找到这个公司名字在express_company中对应的数据
		//如果在express_company中存在该公司，并且这个公司名在deliverycompany中没有对应其他公司(此时该公司名可能对应company这一个公司，也可能不对应一个公司，即company之前没存公司名)
		if(expresscompanylist.size()== 1 && ((deliverycompanylist.size() == 1 && deliverycompanylist.get(0).getId().equals(company.getId())) || (deliverycompanylist.size() == 0))){
			j.setSuccess(true);
		}else{//出现异常，给前台一个反馈
			if(expresscompanylist.size() != 1){//如果该身份证号在express_company中找到两条以上记录或不存在记录					
				infomap.put("expresscompanysize", 1);							
			}else if((deliverycompanylist.size() ==1 && !deliverycompanylist.get(0).getId().equals(company.getId()) || deliverycompanylist.size() > 1)){
				infomap.put("deliverycompanysize", 1);//如果该身份证号在deliverycompany中对应到了其他的人员
			}
				j.setSuccess(false);
		}		
		j.setAttributes(infomap);
			
		return j;
	}
	/**
	 *
	 * @Title: saveRoleUser
	 * @Description: 设置角色信息
	 * @author 孟凡岭
	 * @param @param user
	 * @param @param roleidstr
	 * @return void 返回类型
	 * @throws
	 */
	protected void saveRoleUser(TSUser user, String roleidstr) {
		String[] roleids = roleidstr.split(",");
		for (int i = 0; i < roleids.length; i++) {
			TSRoleUser rUser = new TSRoleUser();
			TSRole role = this.systemService.getEntity(TSRole.class, roleids[i]);
			rUser.setTSRole(role);
			rUser.setTSUser(user);
			this.systemService.save(rUser);

		}
	}

	/**
	 *
	 * @Title: loadRole
	 * @Description: 编辑员工时加载相关的角色信息
	 * @author 孟凡岭
	 * @param @param manId
	 * @param @param request
	 * @param @return
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(params = "loadRole")
	@ResponseBody
	public Map<String, Object> loadRole(String manId, HttpServletRequest request) {
		DeliveryManVO man = this.deliveryManService.get(DeliveryManVO.class, manId);
		List<TSRoleUser> roleUsers = this.systemService.findByProperty(TSRoleUser.class, "TSUser.id", man.getsUser().getId());
		String roleId = "";
		String roleName = "";
		if (roleUsers.size() > 0) {
			for (TSRoleUser tRoleUser : roleUsers) {
				roleId += tRoleUser.getTSRole().getId() + ",";
				roleName += tRoleUser.getTSRole().getRoleName() + ",";
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleId", roleId);
		map.put("roleName", roleName);
		map.put("loginUserName", man.getLoginUserName());
		return map;
	}

	/**
	 *
	 * @Title: editCompany
	 * @Description: 修改公司信息跳转
	 * @author 孟凡岭
	 * @param @return
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(params = "editCompany")
	public String editCompany(String id, HttpServletRequest request) {
		DeliveryCompanyVO vo = this.deliveryCompanyService.get(DeliveryCompanyVO.class, id);
		request.setAttribute("company", vo);

		return "dop/deliveryCompany/deliveryCompanyEdit";
	}

	/**
	 *
	 * @Title: queryManList
	 * @Description: 通过公司号查询配送员信息
	 * @author 孟凡岭
	 * @param @param man
	 * @param @param companyId
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @param request
	 * @param @return
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(params = "queryManList")
	@ResponseBody
	public Map<String, Object> queryManList(DeliveryManVO man, String companyId, int pageNum, int pageSize, HttpServletRequest request, HttpServletResponse response) {
		try {
			TSUser user = ResourceUtil.getSessionUserName();
			// DeliveryManVO delMan =
			// this.deliveryManService.queryByUserId(user.getId());
			// if ((delMan == null) ||
			// (!delMan.getDeliveryCompany().getId().equals(companyId))) {
			// response.sendRedirect("loginController.do?login");
			// return null;
			// } else {
			Map<String, Object> map = this.deliveryManService.queryManListPageByCompanyId(man, companyId, pageNum, pageSize);
			return map;
			// }
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new HashMap<String, Object>();
		}
	}

	/**
	 *
	 * @Title: open
	 * @Description: 启用配送公司
	 * @author 孟凡岭
	 * @param @return
	 * @return AjaxJson 返回类型
	 * @throws
	 */
	@RequestMapping(params = "open")
	@ResponseBody
	public AjaxJson open(@RequestParam(value = "ids[]", required = false) String[] ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			this.deliveryCompanyService.updateStatus(ids, 1);
			j.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			j.setSuccess(false);
		}
		return j;
	}

	/**
	 *
	 * @Title: open
	 * @Description: 停用配送公司
	 * @author 孟凡岭
	 * @param @return
	 * @return AjaxJson 返回类型
	 * @throws
	 */
	@RequestMapping(params = "stop")
	@ResponseBody
	public AjaxJson stop(@RequestParam(value = "ids[]", required = false) String[] ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			List<String> canStopIdList = this.deliveryCompanyService.getCanStopCompanyId(ids);
			String[] canStopIds = new String[canStopIdList.size()];
			for(int i = 0; i < canStopIdList.size(); i ++){
				canStopIds[i] = canStopIdList.get(i);
			}
			this.deliveryCompanyService.updateStatus(canStopIds, 2);
			if(canStopIds.length == 0){
				j.setSuccess(false);
			}else{
				Map successNumMap = new HashMap<String,Object>();
				successNumMap.put("num", canStopIds.length);
				j.setAttributes(successNumMap);
				j.setSuccess(true);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			j.setSuccess(false);
		}
		return j;
	}

}
